<?php

namespace app\resources\model;

use think\facade\Cache;
use app\resources\tasks\PushTask;

class WebSocket extends BaseModel
{
    
    /**
     * 推送消息
     *
     * @param array $param
     * @return void
     */
    public static function push(array $param)
    {
        app('swoole.server')->task([ PushTask::class, $param]);
    }

    /**
     * 推送消息 - 所有用户
     *
     * @param array $param
     * @return void
     */
    public static function pushAllUser(array $param)
    {
        $uids = self::where('action','web')->distinct(true)->column('uid');
        foreach($uids as $uid){
            app('swoole.server')->task([ PushTask::class, [
                'uid'=>$uid,
                'msg'=>$param
            ]]);
        }
    }

    /**
     * 推送节点消息
     *
     * @param array $param
     *  -- uid 
     *  -- msg
     * @param array $isCallKack 是否回调
     * @return void
     */
    public static function pushNodeCmd(array $param,$isCallKack=true)
    {
        if( $msgs = Cache::get(md5(json_encode($param['msg']))) ){
            return $msgs;	
        }
        // 加密
        if( $param['msg']['type'] == 'cmd' || $param['msg']['type'] =='cmd:host' ){
            $param['msg']['body'] = base64_encode($param['msg']['body']);
        }
        // 发送
        self::push($param);
        // 获取执行回调
        if($isCallKack){
            Cache::set('while',1,10);
            while (Cache::get('while')) {
                if(  $msgs = Cache::get(md5(json_encode($param['msg']))) ){
                    return $msgs;	
                    break;     // 终止循环
                }
            }
            return false;
        }else{
            return true;
        }
    }
    

}